import {SUCCESS, getWallet, getBtcPrice,getEosAddress } from '@/api'
import { numberUtils } from '@/utils'
let walletList = JSON.parse(localStorage.walletList || '[]')
let stakeWalletList = JSON.parse(localStorage.stakeWalletList || '[]')
const state = () => ({
  wallet:{},
  walletList: walletList,
  stakeWallet: {},
  stakeWalletList: stakeWalletList,
  eosAddress: '',
  symbol: localStorage.symbol,
})

const getters = {
  
}

const mutations = {
  updateWallet (state, wallet) {
    state.walletList = wallet
    state.wallet = wallet.reduce((obj, item)=>{obj[item.symbol] = item; return obj}, {})
    localStorage.walletList = JSON.stringify(wallet)
  },
  updateStakeWallet (state, wallet) {
    state.stakeWalletList = wallet
    state.stakeWallet = wallet.reduce((obj, item)=>{obj[item.symbol] = item; return obj}, {})
    localStorage.stakeWalletList = JSON.stringify(wallet)
  },
  updateEosAddress (state, eosAddress) {
    state.eosAddress = eosAddress
  },
  updateSymbol(state, symbol){
    state.symbol = symbol
    localStorage.symbol = symbol
  }
  
}

const actions = {
  // get user wallet
  getWallet({dispatch, commit, state, rootState }) {
    return new Promise(resolve => {
      getWallet().then(res => {
        let _wallet = {}
        if(res.rst == SUCCESS){
          let _walletList = res.data.filter(item => {
              return item.type === 1
          })
          _walletList.forEach((item) => {
              item.frozenBalance = numberUtils.add(item.frozenBalance, item.adFrozenBalance).add(item.loanBalance).toString()
          })
          commit('updateWallet', _walletList)

          let _stakeWalletList = res.data.filter(item => {
            return item.type === 2
          })
          _stakeWalletList.forEach((item) => {
              item.frozenBalance = numberUtils.add(item.frozenBalance, item.adFrozenBalance).add(item.loanBalance).toString()
          })
          commit('updateStakeWallet', _stakeWalletList)
        }
        if(rootState.user.sysParams.timestamp==0){
          rootState.user.sysParams.timestamp = res.timestamp || new Date().getTime()
        }
        resolve(res)
      })
    })
  },
  setEosAddress ({dispatch, commit, state }) {
    return new Promise(resolve => {
        getEosAddress().then(res => {
        if(res.rst == SUCCESS){
          commit('updateEosAddress', res.data)
        }
        resolve(res)
      })
    })
  },

}

export default {
  namespaced: true,
  getters,
  state,
  mutations,
  actions
}
